package com.sh.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sh.rbac.domain.entity.LoginUser;
import com.sh.rbac.domain.entity.User;
import com.sh.rbac.domain.enums.UserTypeEnum;
import com.sh.rbac.mapper.MenuMapper;
import com.sh.rbac.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @since 2024-04-07 14:16
 */

@Service
public class LoginService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    //@Autowired
    //private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) {

        // 根据用户名查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(username != null, User::getUsername, username));

        // 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 判断用户类型
        Long userId = UserTypeEnum.isAdmin(user.getUsertype()) ? null : user.getId();


        // 获取用户角色
        //List<Role> roleList = roleMapper.getRolesByUserId(userId);
        //Set<String> roles = roleList.stream().map(Role::getRoleKey).collect(Collectors.toSet());

        // 获取用户权限
        Set<String> permissions = new HashSet<>(menuMapper.getPermissionByUserId(userId));

        // 返回用户详情
        return new LoginUser(user, permissions, null);
    }
}
